import React, { Component } from 'react';
import { BrowserRouter, HashRouter, Switch, Route, Redirect } from 'react-router-dom';
// 导入Routes路由配置信息
import Routes from './routerConfig';
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import './index.css'
import Common from './Common'
// react中的路由本质就是一个组件
class index extends Component {
  render() {
    return (
      <div>
        <BrowserRouter>
          <Route children={(props) => {
            // console.log(props);
            let { history, location } = props;

            return (
              <TransitionGroup>
                <CSSTransition classNames={history.action == 'POP' ? "pop" : "push"} key={location.pathname} timeout={0.5}>
                  <Switch location={location}>
                    {Routes.map((route, index) => {
                      return this.createChildrenRoute(route, index);
                    })}
                  </Switch>
                </CSSTransition>
              </TransitionGroup>

            );
          }}>

          </Route>
        </BrowserRouter>
      </div>
    );
  }
  // 定义函数完成普通路由的构建
  createBaseRoute(route, index) {
    return <Route exact path={route.path}   render={(props)=>{
      return (<Common meta={route.meta} {...props}>
        <route.component {...props}></route.component>
      </Common>)
    }} key={index}></Route>
  }
  // 定义函数完成子路由的构建
  createChildrenRoute(route, index) {
    // 获取当前路由的相关配置信息
    let { path, component: Father, children } = route;

    if (children) {
      return <Route key={index} path={path} children={() => {
        return (
          <Father>
            <Switch>
              {
                children.map((route2, index2) => {
                  return this.createChildrenRoute({ ...route2, path: path + '/' + route2.path }, `${index}-${index2}`);
                })
              }
              <Redirect from={path} to={path + '/' + children[0].path}></Redirect>
            </Switch>
          </Father>
        )
      }} />
    } else {
      // 生成普通路由实例
      return this.createBaseRoute(route, index);
    }
  }
}

export default index;